<template>
  <div class="accountManagement_view" v-loading="loading">
    <div class="accountManagement" ref="accountManagement" :style="{ width: drawer ? 'calc(100% - 210px)' : '100%' }">
      <cus-body :tableColumn="tableColumn" :tableData="tableData" :tableBorder="true" :hasPage="false" :operate="true"
        :operateList="operateList" :total="total" :operateWidth="300" @handleClick="handleClick"
        @getNavList="getNavList" :searchCriteriaData="searchCriteriaData" :searchCriteria="searchCriteria">
        <template #operate="slotProps">
          <el-button v-for="(btn, index) in operateList" :key="index"
            @click="handleButtonClick(btn, slotProps.propsData)" type="text" size="small"
            :style="{ color: btn.color || '#409EFF' }">
            {{ btn.name }}
          </el-button>
          <el-upload class="upload_btn" :limit="1" :data="{
            bucketKey: slotProps.propsData.bucketKey
          }" :on-success="handleSuccess" :show-file-list="false" action="/api/autoDesk/models/upload">
            <el-button type="text" size="small">上传</el-button>
          </el-upload>
        </template>
        <template v-slot:searchBtn>
          <el-button @click="createBucket">创建储存桶</el-button>
          <el-button @click="getData">获取元数据</el-button>
        </template>
      </cus-body>
    </div>
    <div class="file_body" v-loading="fileLoading"
      :style="{ width: drawer ? '200px' : '0', marginLeft: drawer ? '10px' : '0' }">
      <div class="one_file" v-for="(data, index) in fileList" @click="showFile(data)">
        <div class="file_icon">
          <img class="file_icon_img" src="@/assets/dwg.png">
        </div>
        <div class="file_name">{{ data.name }}</div>
      </div>
      <div class="one_file">
        <el-upload :limit="1" :data="{
          bucketKey: selectBucketKey
        }" :on-success="handleSuccess" :show-file-list="false" action="/api/autoDesk/models/upload">
          <div class="one_file_upload">
            <div class="file_icon">
              <img class="file_icon_img" src="@/assets/upload.png">
            </div>
            <div class="file_name">上传文件</div>
          </div>
        </el-upload>
      </div>
    </div>
  </div>

  <el-dialog v-loading.fullscreen.lock="fullscreenLoading" v-model="dialogFormVisible" title="新建储存桶" width="500"
    @closed="openedDialog" @opened="openedDialog">
    <el-form ref="ruleFormRef" :model="form" :rules="rules">
      <el-form-item label="buckets name" :label-width="formLabelWidth" prop="bucketsName">
        <el-input v-model="form.bucketsName" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="testDwg">
import CusBody from "@/components/cus-body.vue";
import { buttonNativeTypes, ElMessage, ElMessageBox } from 'element-plus'
import api from '@/plugins/api/index'
import { reactive, ref } from "vue";
import router from "@/router";
// 搜索模块的数据对象
const searchCriteriaData = reactive({
  name: null,
  administratorName: null
})
const drawer = ref(false)
const fullscreenLoading = ref(false)
const createOrEdit = ref('create')
const ruleFormRef = ref()
const accountManagement = ref(null)
const loading = ref(false)
const fileLoading = ref(false)
const form = reactive({
  bucketsName: '',
})
const selectBucketKey = ref(null)
const fileList = ref(null)

const rules = reactive({
  bucketsName: [
    { required: true, message: 'Please input buckets Name', trigger: 'blur' },
  ],
})
const formLabelWidth = '140px'
const dialogFormVisible = ref(false)
const total = ref(100)
// 搜索条件的配置项
const searchCriteria = reactive([
  {
    type: 'input',   // 搜索条件类型，目前支持：input、select、time、date、dateTime
    label: '权限名称',   // 搜索条件的标题
    dataValueName: 'name', // v-model绑定的值
    placeholder: '',    // 搜索框里面的提示内容
    isRequired: false,  // 是否必填
  },
])

// 表格数据
let tableData = ref([])

const operateList = reactive([
  {
    name: '查询文件',
    operateType: 'getObjects'
  },
  {
    name: '查看',
    operateType: 'see'
  },
  {
    name: '删除',
    operateType: 'delete'
  }
])

async function showFile(data) {
  console.log(data.urn)
  const rd = await api.getUrnStatus({
    urn: data.urn
  })
  if (rd.data.status === "success") {
    window.sessionStorage.setItem('urn', data.urn)
    router.push(`/dwgDetail`)
  }else {
     ElMessage({
      type: 'info',
      message: '正在解释中，请稍等',
    })
  }
}

async function getData() {
  const urn = 'dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6YnNjYnVja2V0X3Rlc3QvQlNDLVBFLTAwMDEmMDAwMiUyMC1BJTIwJTVCUGxhbnMlNUQlMjAoMjQxMTA2KXdpdGglMjBUMzMlMjBHcmlkLmR3Zw'
  const res = await api.getMetadata({
    urn: urn
  })
  console.log(res.data.data.metadata)
  getForModelGuid(urn, "e30bd031-d13a-a976-9153-78100829986a")
  getProperties(urn, "e30bd031-d13a-a976-9153-78100829986a")
  postProperties(urn, "e30bd031-d13a-a976-9153-78100829986a")
}

async function getForModelGuid(urn, modelGuid) {
  const res = await api.getForModelGuid({
    urn: urn,
    modelGuid: modelGuid
  })
  console.log(res.data.data)
}

async function postProperties(urn, modelGuid) {
  const res = await api.postProperties({
    urn: urn,
    modelGuid: modelGuid
  })
  console.log(res.data.data)
}

async function getProperties(urn, modelGuid) {
  const res = await api.getProperties({
    urn: urn,
    modelGuid: modelGuid
  })
  console.log(res.data.data)
}

function openedDialog() {
  if (createOrEdit.value === 'create') {
    ruleFormRef.value && ruleFormRef.value.resetFields()
  }
}

function createBucket() {
  createOrEdit.value = 'create'

  dialogFormVisible.value = true
}

function editBuckets(bucketKey) {
  createOrEdit.value = 'edit'
  form.bucketsName = bucketKey
  dialogFormVisible.value = true
}

const submitForm = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log(form)

      addBuckets()
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

async function delBucketBefore(bucketKey) {
  ElMessageBox.confirm('此次操作不可逆，确定是否需要删除？', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning',
  }
  ).then(() => {
    delBucket(bucketKey)
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消',
    })
  })
}

async function delBucket(bucketKey) {
  loading.value = true
  const res = await api.delBucket({
    bucketKey: bucketKey
  })
  const data = res.data
  if (data.code === 200) {
    getCheckBuckets()
  }
  loading.value = false
  console.log(res)
}

async function addBuckets() {
  fullscreenLoading.value = true
  try {
    const res = await api.addBuckets(form)
    console.log(res.data)
    const data = res.data
    if (data.code === 200) {
      console.log(data.data)
      getCheckBuckets()
      dialogFormVisible.value = false
    }
  } catch (err) {
    console.log(err)
  } finally {
    fullscreenLoading.value = false
  }

}

function handleButtonClick(btnType, data) {
  if (btnType.operateType === 'see') {
    getCheckBucketDetail(data.bucketKey)
  } else if (btnType.operateType === 'getObjects') {
    getObjects(data.bucketKey)
  } else if (btnType.operateType === 'delete') {
    delBucketBefore(data.bucketKey)
  }
}

function handleClick(data) {
  console.log(data)
  if (data.operateType === 'see') {
    getCheckBucketDetail(data.bucketKey)
  } else if (data.operateType === 'getObjects') {
    getObjects(data.bucketKey)
  } else if (data.operateType === 'delete') {
    delBucketBefore(data.bucketKey)
  }
}

const handleSuccess = (file) => {
  console.log(file)
  if (drawer.value && file.bucketKey === selectBucketKey.value) {
    getObjects(selectBucketKey.value)
  }
}


async function getObjects(bucketKey) {
  fileLoading.value = true
  drawer.value = true
  selectBucketKey.value = bucketKey
  try {
    const res = await api.getObjects({
      bucketKey: bucketKey
    })
    console.log(res.data)
    const data = res.data
    if (data.code === 200) {
      console.log(data.data)
      fileList.value = data.data
    }
  } catch (err) {
    console.log(err)
  } finally {
    fileLoading.value = false
  }
}

async function getCheckBucketDetail(bucketKey) {
  try {
    const res = await api.getCheckBucketDetail({
      bucketKey: bucketKey
    })
    console.log(res.data)
    const data = res.data
    if (data.code === 200) {
      console.log(data.data)
    }
  } catch (err) {
    console.log(err)
  }
}

// 表格的配置项
const tableColumn = reactive([
  {
    label: '存储桶名称',
    prop: 'bucketKey',
    isFixed: false,
    openStol: false,
    width: null,
  },
  {
    label: '创建时间',
    prop: 'createdDate',
    isFixed: false,
    openStol: false,
    width: null,
  },
  {
    label: 'policyKey',
    prop: 'policyKey',
    isFixed: false,
    openStol: false,
    width: null,
  }
])

async function getCheckBuckets() {
  loading.value = true
  try {
    const res = await api.getCheckBuckets()
    console.log(res.data)
    const data = res.data
    if (data.code === 200) {
      console.log(data.data)
      tableData.value = data.data?.items
    }
  } catch (err) {
    console.log(err)
  } finally {
    loading.value = false
  }
}


getCheckBuckets()

</script>
<style scoped lang="scss">
.accountManagement_view {
  width: 100%;
  height: 100%;
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;
}

.accountManagement {
  height: 100%;
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  -webkit-transition: width 0.2s;
  /* For Safari 3.0 to 6.0 */
  transition: width 0.2s;
  /* For modern browsers */
}

.file_body {
  height: 100%;
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: auto;
  display: -webkit-flex;
  display: -moz-flex;
  flex-wrap: wrap;
  align-content: flex-start;
  align-items: flex-start;
  -webkit-transition: width 0.2s;
  /* For Safari 3.0 to 6.0 */
  transition: width 0.2s;
  /* For modern browsers */

  .one_file {
    width: 50%;
    box-sizing: border-box;
    padding-top: 10px;
    min-height: 100px;
    height: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    display: -webkit-flex;
    display: -moz-flex;
    flex-direction: column;
    cursor: pointer;
    box-sizing: border-box;
    border: 4px solid #ffffff;
    border-radius: 10px;
    -webkit-transition: border-color 0.2s;
    /* For Safari 3.0 to 6.0 */
    transition: border-color 0.2s;
    /* For modern browsers */

    &:hover {
      border-color: cornflowerblue
    }

    .one_file_upload {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      display: -webkit-flex;
      display: -moz-flex;
      flex-direction: column;
    }

    .file_icon {
      width: 100%;
      height: auto;
      text-align: center;
      margin-bottom: 2px;

      .file_icon_img {
        width: 40px;
        height: auto;
      }
    }

    .file_name {
      width: 100%;
      height: 40px;
      text-align: center;
      font-size: 12px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.bodyView {
  width: 100%;
  height: auto;
  display: flex;
  display: -webkit-flex;
  display: -moz-flex;
  gap: 10px;
  flex-wrap: wrap;
}

.upload_btn {
  display: inline-block;
}
</style>